/*
 * Ext GWT - Ext for GWT Copyright(c) 2007, 2008, Ext JS, LLC. licensing@extjs.com http://extjs.com/license
 */
package cn.taokuaidi.wangwang.buyer.client;

import java.util.List;

import cn.taokuaidi.wangwang.client.constants.AppEvents;
import cn.taokuaidi.wangwang.client.context.BuyerDataEventContext;
import cn.taokuaidi.wangwang.client.model.ExpressDO;
import cn.taokuaidi.wangwang.client.model.OrderDO;
import cn.taokuaidi.wangwang.client.model.StatusInfo;
import cn.taokuaidi.wangwang.client.util.JavaScriptUtils;
import cn.taokuaidi.wangwang.client.widget.BaseEventCenter;

import com.extjs.gxt.ui.client.Events;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.core.XTemplate;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.util.Util;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.ListView;
import com.extjs.gxt.ui.client.widget.Viewport;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;

public class BuyerView extends Viewport {

    private ListStore<OrderDO> store;
    private XTemplate          detailTp;
    private ListView<OrderDO>  view;
    private LayoutContainer    details;
    private ContentPanel       center;
    private ContentPanel       east;

    private void loadData() {
        store = BuyerDataEventContext.getStore();
        view.setStore(store);
        if (store.getCount() > 0) {
            detailTp.overwrite(details.getElement(), Util.getJsObject(store.getAt(0)));
        }
        view.refresh();
    }

    private String getTipSeller(OrderDO order) {
        String retVal = "<a href=javascript:sendMsg(\"" + order.get("seller_nick") + "\",\"" + getToSellerMsg(order)
                        + "\")><img src='/images/ww.gif' border=0></a>";
        return retVal;
    }

    private String getToSellerMsg(OrderDO order) {
        String sellerNick = order.get("seller_nick");
        String title = order.get("title");
        String msg = "hi," + sellerNick + "\n\n" + "我在您处购买的:" + title + "\n\n快递信息设置不正确啊，请检查一下\n\n谢谢!";
        return format(msg);
    }

    private String format(String str) {
        str = JavaScriptUtils.javaScriptEscape(str);
        return str;
    }

    private String getExpressInfo(OrderDO order) {
        StringBuffer retVal = new StringBuffer("");
        ExpressDO express = order.getExpress();
        if (express != null) {

            retVal.append("<b>" + express.getAgent().getName() + ":" + express.getNo() + "&nbsp;&nbsp;不正常就"
                          + getTipSeller(order) + "</b>");
            List<StatusInfo> status = express.getStatuses();
            if (status != null) {
                for (StatusInfo item : status) {
                    String time = item.getHappenTime();
                    time = time.replace("T", " ");
                    time = time.replace("+08:00", "");
                    retVal.append("<span>" + time + "   " + item.getInfo() + "</span>");

                }
            }
        } else {
            retVal.append("<b>卖家尚未设置快递信息，赶紧联系对方吧，&nbsp;&nbsp;" + getTipSeller(order) + "<br>打开聊天对话框后，鼠标右键，选择粘贴即可哦</b>");
        }
        return retVal.toString();
    }

    public BuyerView() {
        final BorderLayout layout = new BorderLayout();
        setLayout(layout);
        this.setId("img-chooser-dlg");
        east = new ContentPanel();
        east.setHeaderVisible(false);
        east.setScrollMode(Scroll.AUTOY);
        center = new ContentPanel();
        center.setHeaderVisible(false);
        center.setScrollMode(Scroll.AUTOY);

        detailTp = XTemplate.create(getDetailTemplate());

        view = new ListView<OrderDO>() {

            @Override
            protected OrderDO prepareData(OrderDO order) {
                order.set("expressInfo", getExpressInfo(order));
                return order;
            }
        };
        view.setId("img-chooser-view");
        view.setTemplate(getTemplate());
        view.setBorders(false);
        view.setStore(store);
        view.setItemSelector("div.thumb-wrap");
        view.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        view.getSelectionModel().addListener(Events.SelectionChange, new Listener<SelectionChangedEvent<BeanModel>>() {

            public void handleEvent(SelectionChangedEvent<BeanModel> be) {
                onSelectionChange(be);
            }
        });
        east.add(view);

        details = new LayoutContainer();
        details.setBorders(true);
        details.setStyleAttribute("backgroundColor", "white");
        ContentPanel tipPanel = new ContentPanel();
        tipPanel.setHeaderVisible(false);
        tipPanel.setIconStyle("incon-text");
        tipPanel.addText("<font color='#FF6600' size=2>亲爱的用户，如果未出现最新订单，是由于淘宝API访问的时效引起的，需要您重新授权并刷新本页，您可能需要再次输入淘宝网的用户名与密码，并对我们给予授权确认，谢谢。<a href='/gwt_buyer/login_taobao'>点击此处授权</a></font>");
        if (isExtendTime()) {
            center.add(tipPanel, new RowData(1, -1, new Margins(4)));
        }
        center.add(details, new RowData(1, -1, new Margins(4)));

        BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);
        centerData.setMargins(new Margins(0));

        BorderLayoutData eastData = new BorderLayoutData(LayoutRegion.EAST, 100);
        eastData.setMargins(new Margins(0));
        eastData.setSplit(true);
        eastData.setCollapsible(true);
        add(east, eastData);
        add(center, centerData);
    }

    @Override
    protected void onRender(Element parent, int index) {
        super.onRender(parent, index);
        Dispatcher.get().addController(new BaseEventCenter() {

            @Override
            public void handleEvent(AppEvent<?> event) {
                if (event.type == AppEvents.BUYER_DATA_LOADED) {
                    loadData();
                }
            }
        });

        BuyerDataEventContext.load();

    }

    private void onSelectionChange(SelectionChangedEvent<BeanModel> se) {
        if (se.getSelection().size() > 0) {
            detailTp.overwrite(details.getElement(), Util.getJsObject(se.getSelection().get(0)));
        } else {
            details.el().setInnerHtml("");
        }
    }

    private boolean isExtendTime() {
        String value = DOM.getElementById("isAPIExtendTime").getAttribute("value");
        if ("false".equalsIgnoreCase(value)) {
            return true;
        }
        return false;
    }

    private native String getTemplate() /*-{
                                                                                                                return ['<tpl for=".">',
                                                                                                                '<div class="thumb-wrap" id="{title}" style="border: 1px solid white">',
                                                                                                                '<div class="thumb"><img src="{pic_path}" width="80" height="80" title="{title}"></div>',
                                                                                                                '</div>',
                                                                                                                '</tpl>',
                                                                                                                '<div class="x-clear"></div>'].join("");
                                                                                                                }-*/;

    public native String getDetailTemplate() /*-{
                                                                                                                 return ['<div class="details">',
                                                                                                                   '<tpl for=".">',
                                                                                                                   '<img src="{pic_path}" width="100" height="100"><div class="details-info">',
                                                                                                                   '<span>{title}</span>',
                                                                                                                   '{expressInfo}',
                                                                                                                   '</div>',
                                                                                                                   '</tpl>',
                                                                                                                   '</div>'].join("");
                                                                                                                }-*/;
}
